const app = getApp();

Page({
  data: {
    imgUrl: '',
    orders: [],
    activeTab: 0, // 当前选中的标签索引，0代表"全部"
    statusMap: {
      0: '',         // 全部
      1: '待付款',
      2: '已支付',
      3: '待评价',
      4: '订单已取消'
    }
  },
  onPullDownRefresh(){
    this.onLoad()
},
  onLoad() {
    this.fetchOrders();
    this.setData({
      imgUrl: app.imgUrl
    })
    wx.stopPullDownRefresh()
  },

  onTabChange(event) {
    const activeTab = event.detail.index;
    this.setData({ activeTab });
    this.fetchOrders();
  },

  fetchOrders() {
    const token = wx.getStorageSync('token');
    const status = this.data.statusMap[this.data.activeTab]; // 根据当前选中的标签索引获取对应的订单状态

    wx.request({
      url: app.apiUrl + '/orders/seller/orders',  // 卖家的订单接口
      method: 'GET',
      header: { "token": token },
      data: { status },  // 根据状态过滤
      success: res => {
        if (res.data.code === 1) {
          this.setData({
            orders: res.data.data
          });
        } else {
          wx.showToast({ title: '获取订单失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '请求失败，请稍后重试', icon: 'none' });
      }
    });
  },

  viewOrderDetails(e) {
    const orderId = e.currentTarget.dataset.id;
    const buyerId = e.currentTarget.dataset.buyerid;
    console.log(e)
    wx.navigateTo({
      url: `/pages/orders/detail/detail?orderId=${orderId}&buyerId=${buyerId}`
    });
  },

  // 卖家发货功能
  handleShip(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.request({
      url: `${app.apiUrl}/orders/seller/ship/${orderId}`,  // 发货的接口
      method: 'POST',
      header: { "token": wx.getStorageSync('token') },
      success: res => {
        if (res.data.code === 1) {
          wx.showToast({ title: '发货成功', icon: 'success' });
          this.fetchOrders();  // 发货成功后刷新订单列表
        } else {
          wx.showToast({ title: res.data.msg, icon: 'none' });
        }
      }
    });
  },

  cancelOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.request({
      url: `${app.apiUrl}/orders/cancel/${orderId}`,
      method: 'POST',
      header: { "token": wx.getStorageSync('token') },
      success: res => {
        if (res.data.code === 1) {
          wx.showToast({ title: '订单已取消', icon: 'success' });
          this.fetchOrders();  // 取消成功后刷新订单列表
        } else {
          wx.showToast({ title: res.data.msg, icon: 'none' });
        }
      }
    });
  }
});
